<template>
  <div>
    <div class="title" style="display: flex;user-select: none;">
      <div style="flex:1;">退包装物</div>
      <div style="margin-right: 20px;font-size: 13px;" @click="showBillPop=true">手工查询</div>
      <div style="margin-right: 20px;font-size: 13px;" @click="help">帮助</div>
      <div style="margin-right: 20px;font-size: 13px;" @click="showBill('last')">上一张</div>
      <div style="margin-right: 20px;font-size: 13px;" @click="showBill('next')">下一张</div>
    </div>
    <el-dialog v-model="showPop" title="修改单位" :z-index="9" :width="300">
      <tiny-select v-model="unit" placeholder="请选择" size="large" @change="changeUnit">
        <tiny-option v-for="(item, index) in units" :key="index" :label="item.name" :value="item.id"> </tiny-option>
      </tiny-select>
    </el-dialog>
    <el-dialog v-model="helpPop" draggable title="本页帮助说明">
      <el-image src="https://download.sanzhiyun.cn/web5/help/backhelp.png"></el-image>
    </el-dialog>
<!--    <el-empty v-if="!buId" description="请扫描销售二维码"></el-empty>-->
    <div style="display: flex;">
      <div style="margin-right: 1px;margin-top: 10px;">
        <t-grid
                 :offsetHeight="8"
                 :data-list="currentInvoice.infos"
                 :fields="columns"
                 @editClosed="editClose"
                 @cellClick="cellClick"
                 :showFooter="false"
        />
      </div>
      <div style="flex: 1;">
        <div style="margin-top: 10px;">
          <t-grid ref="saleListRef" :gridHeight="bh" :fields="billsCols" :showFooter="false" :dataList="billList" @cellClick="cellClickBill" />
          <div style="text-align: center;padding-top: 5px;">
            <lbtn size="large" type="primary" @click="save" v-if="!saved">保存并审核</lbtn>
<!--            <lbtn size="large" type="primary" @click="add"  >新增</lbtn>-->
            <lbtn  size="large" type="primary" @click="clear" v-if="saved">新增退货</lbtn>
            <lbtn style="margin-left: 200px;" size="large" @click="print" v-if="saved">打印汇总小票</lbtn>
          </div>
        </div>
        <tiny-divider content-position="center">商品汇总</tiny-divider>
        <t-grid ref="goodListRef"  :gridHeight="gh" :fields="gcols" :dataList="gpList" />
      </div>
    </div>
    <el-dialog v-model="showBillPop" title="手工查询单据" close-on-press-escape destroy-on-close >
      <div style="display: flex;">
        <ltext v-model="billNo" placeholder="请输入准确的销售单据号"></ltext>
        <lbtn style="margin-left: 20px;" @click="doSearch" icon="search" >查询</lbtn>
      </div>
    </el-dialog>
    <div id="printHtml" v-html="showPrint" style="position: absolute;top: -9999px;left: -9999px;" ></div>
  </div>
</template>
<script>
// 退包装物品
import tool from "@/utils/tool";
import bus from "@/store/bus.js";
import { Select, Option,   } from '@opentiny/vue'
import { Split,Divider } from '@opentiny/vue'
import Doprint from "../doprint.vue";
import Lbtn from "../../../lui/lbtn.vue";
export default {
  name: "wrapperBack",
  components: {
    Lbtn,
    Doprint,
    TinySelect: Select,
    TinyOption: Option,
    TinySplit: Split,
    TinyDivider: Divider
  },
  data () {
    return {
      code: '',
      helpPop: false,
      showPop: false,
      columns:[
        {type: 'index', width: 40},
        {field: 'name', title: '商品名称', width: 200,align: 'left'},
        {field: 'specs', title: '规格', width: 70},
        {field: 'unit', title: '单位', width: 70},
        {field: 'qty', title: '数量',align:'right', width: 90,editor: {component: 'input',attrs:{type:'number'}, autoselect: true,},},
        {field: 'price', title: '单价',align:'right',formatter:'formatMoney', width: 90,editor: {component: 'input',attrs:{type:'number'}, autoselect: true}},
        {field: 'amount', title: '金额',align:'right',formatter:'formatMoney', width: 90,editor: {component: 'input',attrs:{type:'number'}, autoselect: true}},
        {field: 'remark', title: '备注', width: 90,editor: {component: 'input', autoselect: true}},
      ],
      billsCols:[
        {type: 'index', width: 50},
        {field: 'billNo', title: '票号', width: 120,align: 'left'},
        {field: 'buName', title: '客户', width: 160,align: 'left'},
        {field: 'arrearsReal', title: '原金额', width: 100,align: 'right',formatter:'formatMoney'},
        {field: 'dikou', title: '退货抵扣', width: 100,align: 'right',formatter:'formatMoney'},
        {field: 'leftAmount', title: '结余金额', width: 100,align: 'right',formatter:'formatMoney'},
        {title: '操作',width: 60,btns:[{label: '删除',click: (row) => {
          this.delRow(row)
            }}]}
      ],
      gcols:[
        {type: 'index', width: 50},
        {field: 'invName', title: '商品', width: 300,align: 'left'},
        {field: 'spec', title: '规格', width: 80,align: 'center'},
        {field: 'unit1', title: '单位', width: 80,align: 'center'},
        {field: 'qty', title: '数量', width: 100,align: 'right',sum: true},
        {field: 'assQty', title: '辅助数量', width: 140,align: 'right'},
      ],
      currentRow: {},
      units: [],
      unit: '',
      billId: '',
      popOpened: false,
      bh: 300,
      billList: [],
      currentInvoice: {},
      saved: false,
      sendPrintName: '',
      salePrintName: '',
      showPrint: '',
      showBillPop: false,
      billNo: '',
      billsId: 0
    }
  },
  created() {
    this.getPrintName()
    bus.$on('scan-ret', this.scanRet)
  },
  unmounted () {
    bus.$off('scan-ret', this.scanRet)
  },
  computed: {
    gh () {
      return window.innerHeight - this.bh - 170
    },
    gpList () {
      let detail = []
      for (let i = 0; i < this.billList.length; i++) {
        this.billList[i].infos.map(row => {
          detail.push(row)
        })
      }
      let gp = tool.xe.groupBy(detail,'invId')
      let gparr = []
      for(let x in gp) {
        let g = {}
        let qty = 0
        let item = gp[x]
        for (let i = 0; i < item.length; i++) {
          g.invId = item[i].invId
          g.invName = item[i].invName
          g.locationId = item[i].locationId
          g.locationName = item[i].locationName
          g.unit = item[i].unit
          g.unit1 = item[i].unit1
          g.unit2 = item[i].unit2
          g.price = item[i].price
          g.calNum = item[i].calNum
          g.spec = item[i].spec
          let subqty = item[i].unit === item[i].unit1 ? tool.xe.multiply(item[i].qty, item[i].calNum):item[i].qty
          qty = tool.xe.add(qty, subqty)
        }
        if(qty !== 0) {
          g.qty = qty
          g.assQty = tool.toAssQty(g)
          g.qty = tool.xe.round(tool.xe.divide(qty, g.spec),2)
          gparr.push(g)
        }
      }
      return gparr
    }
  },
  watch: {
    currentInvoice: {
      deep: true,
      handler: (val) => {
        let sum = tool.xe.sum(val.infos,'amount')
        val.dikou = sum
        val.leftAmount = val.arrearsReal - sum
      }
    }
  },
  methods: {
    add () {
      this.billList.push({
        billNo: 'x1',buName: 'x',arrearsReal: '3',dikou: '3', leftAmount: '1'
      })
      this.scrollToRow()
    },
    scrollToRow () {
      this.$nextTick(() => {
        let lastRow = this.$refs.saleListRef.getData(this.billList.length - 1)
        let lastRow1 = this.$refs.goodListRef.getData(this.gpList.length - 1)
        setTimeout(() => {
          this.$refs.saleListRef.scrollToRow(lastRow)
          this.$refs.goodListRef.scrollToRow(lastRow1)
        }, 100)
      })
    },
    closedPop () {
      this.popOpened = false
    },
    help () {
      this.helpPop = true
    },
    gpback () {
      this.popOpened = true
      this.$refs.gpbackRef.open()
    },
    doSearch () {
      if(this.billNo) {
        tool.post('bill/getIdByNo', {billNo: this.billNo}).then(ret => {
          if(ret.stat) {
            this.scanRet({code: ret.data})
            this.showBillPop = false
          }
        })
      }
    },
    cellClick (cell) {
      if(cell.column.property === 'unit') {
        this.showPop = true
        this.currentRow = cell.row
        this.unit = cell.row.unit
        this.units = []
        this.units.push({id: cell.row.unit1, name: cell.row.unit1})
        if(cell.row.unit2)
          this.units.push({id: cell.row.unit2, name: cell.row.unit2})
      }
    },
    cellClickBill (cell) {
      this.currentInvoice = cell.row
    },
    changeUnit (val) {
      this.currentRow.unit = val
      this.showPop = false
    },
    scanRet ({ code }) {
      let arr = code ? code.split('-') : []
      if (arr.length !== 2) {
        return tool.err('二维码识别错误，请重试')
      }

      if(this.saved) {
        this.clear()
      }
      setTimeout(() => {
        if(this.popOpened) {
          // 弹出汇总小票
          tool.post('deliver/getBackRel', {billId: arr[1]}, true).then(ret => {
            this.$refs.gpbackRef.addData(ret.data)
          })
        }
        else {
          this.billId = arr[1]
          this.code = code
          this.getList()
        }
      }, 10)
    },
    getList () {
      tool.post('deliver/backList', {code: this.code}, true).then(ret => {
        if(ret.stat) {
          let billNo = this.billList.filter(row => {
            return row.billNo === ret.data.billNo
          })
          if(billNo.length === 0) {
            ret.data.list.map(row => {
              row.locationId = ret.data.locationId
              row.locationName = ret.data.locationName
              row.calNum = row.spec
              row.invId = row.id
              row.invName = row.name
            })
            let invoice = {
              billNo: ret.data.billNo,
              billId: ret.data.billId,
              billDate: tool.getDay(),
              buName: ret.data.buName,
              buId: ret.data.buId,
              arrearsReal: ret.data.arrearsReal,
              dikou: 0,
              leftAmount: ret.data.arrearsReal,
              infos: ret.data.list
            }
            this.currentInvoice = invoice
            this.billList.push(invoice)

            this.scrollToRow()
          }
        }
      })
    },
    delRow (row) {
      if(this.saved) return tool.err('不能删除已保存并审核的单据')
      for (let i = 0; i < this.billList.length; i++) {
        if(this.billList[i].billNo === row.billNo) {
          this.billList.splice(i, 1)
          this.currentInvoice = {}
        }
      }
    },
    editClose (cell) {
      let row = cell.row
      let field = cell.column.property
      if(field === 'qty') {
        row.qty = Math.abs(tool.xe.toNumber(row.qty))
        row.amount = tool.xe.toFixed(tool.xe.multiply(row.qty, row.price), 2)
      }
      if(field === 'price') {
        row.price = Math.abs(tool.xe.toNumber(row.price))
        row.amount = tool.xe.toFixed(tool.xe.multiply(row.qty, row.price), 2)
      }
      if(field === 'amount') {
        row.amount = Math.abs(tool.xe.toNumber(row.amount))
        if(tool.xe.toNumber(row.qty)) {
          row.price = tool.xe.toFixed(tool.xe.divide(row.amount, row.qty), 2)
        }
        else {
          row.amount = 0
        }
      }
    },
    save () {
      if(this.billList.length === 0) return tool.warning('没有要退货的票据')
      if(this.gpList.length === 0) return tool.warning('没有要退货的商品')
      tool.post('bill/saveBack', {data: this.billList},true).then(ret => {
        if(ret.stat) {
          this.saved = true
          this.billsId = ret.data
        }
      })
    },
    clear () {
      this.billList = []
      this.currentInvoice = {}
      this.saved = false
    },
    print () {
      this.sendPrint()
    },
    openSearch () {
      this.billNo = ''
      this.searchList = []
      this.showBillPop = true
    },
    // 取打印机名称
    getPrintName () {
      tool.post('deliver/getPrintName', {}).then(ret => {
        if (ret.stat) {
          if (ret.data.length === 0) return tool.err('没有发现打印机')
          let sendPrints = []
          let salePrints = []
          for (let i = 0; i < ret.data.length; i++) {
            if (ret.data[i].sendPrintName) sendPrints.push(ret.data[i].sendPrintName.trim())
            if (ret.data[i].salePrintName) salePrints.push(ret.data[i].salePrintName.trim())
          }
          const LODOP = (typeof getCLodop === 'function') ? getCLodop() : ''
          if (LODOP) {
            let c = LODOP.GET_PRINTER_COUNT()
            if (!c) return tool.err('未发现打印机')
            for (let i = 0; i < c; i++) {
              let name = LODOP.GET_PRINTER_NAME(i)
              if (!name) continue
              if (sendPrints.indexOf(name.trim()) !== -1) {
                this.sendPrintName = name
              }
              if (salePrints.indexOf(name.trim()) !== -1) {
                this.salePrintName = name
              }
            }
          }
        }
      })
    },
    sendPrint() {
      let gpGoods = this.gpList
      if(gpGoods.length === 0) {
        return tool.err('没有汇总数据')
      }
      LODOP.PRINT_INIT("汇总小票打印");
      LODOP.SET_LICENSES("","C748D766DD08B5AE84E6BC2F3A546E6C7C9","","");
      let tbhtml = '<table style="border-collapse:collapse;width:270px;"><tbody>'
      //
      tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px;width:270px;'>商品汇总</td></tr>"
      for (let i = 0; i < gpGoods.length; i++) {
        tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;">'+gpGoods[i].invName+'</td><td style="width: 70px;text-align: right;">'+gpGoods[i].assQty+'</td></tr>'
      }
      tbhtml += "<tr><td style='border-bottom: 1px solid black;'></td><td style='border-bottom: 1px solid black'></td></tr>"
      tbhtml += "<tr><td colspan='2' style='border-top: 1px solid black;height: 110px;'></td> </tr>"
      tbhtml += '</tbody></table>'
      this.showPrint = tbhtml
      let dom = document.getElementById("printHtml");
      dom.innerHTML = tbhtml


      setTimeout(() => {
        dom = document.getElementById("printHtml");
        let rects = dom.getClientRects()
        let barTop = tool.minus(rects[0].height, 120)
        if (barTop < 300) barTop += 20
        // LODOP.ADD_PRINT_BARCODE(barTop+'px', '90px', '100px', '100px', 'QRCode', '180001-' + item.id);
        this.top = barTop
        LODOP.SET_PRINT_PAGESIZE(3, '80mm',45,"") //这里3表示纵向打印且纸高“按内容的高度”；1385表示纸宽138.5mm；45表示页底空白4.5mm
        LODOP.ADD_PRINT_TABLE(40, 0, 800, rects[0].height, tbhtml)

        if (LODOP.SET_PRINTER_INDEX(this.sendPrintName)) {
          // LODOP.PREVIEW();
          LODOP.PRINT();
          this.chosePrint = false
          // LODOP.PREVIEW();
          //   if (LODOP.CVERSION) {
          //     CLODOP.On_Return = (TaskID,Value)=> {
          //       if (Value !== 0 || Value !== false) {
          //         tool.post('print/billPrintSuc', {cargoId: item.id}).then(ret => {})
          //       }
          //     }
          //   }

        } else {
          tool.err('读取小票打印机失败')
        }
      }, 50)
    },
    showBill (type) {
      tool.post('bill/showBill', {type: type,billsId: this.billsId}).then(ret => {
        if(ret.stat) {
          this.billList = JSON.parse(ret.data.content)
          this.billsId = ret.data.id
          this.saved = true
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
fieldset {
  padding: 5px;
  margin: 0;
  border: 1px solid #d3dce6;
}
.demo-split-pane.no-padding {
  height: 100%;
  padding: 0;
}
.title {
  text-align: center;
  font-weight: bold;
  font-size: 22px;
  background-color: #01aaee;
  color: white;
  height: 40px;
  line-height: 40px;
}
</style>